package com.sds.sweng.swat.miplatform.service.viewers;

import java.util.List;

import org.dom4j.Node;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

import com.sds.sweng.swat.miplatform.service.pages.ServiceControlArea;

public class ServiceDatasetViewer extends Composite {

	private ListViewer serviceList;

	private ServiceControlArea area;

	public ServiceDatasetViewer(Composite parent) {
		super(parent, SWT.NONE);

		setLayout(new FillLayout());

		init();
	}

	public void setArea(ServiceControlArea area) {
		this.area = area;
	}

	private void init() {
		serviceList = new ListViewer(this, SWT.SINGLE | SWT.V_SCROLL);

		serviceList.setContentProvider(new IStructuredContentProvider() {

			public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
				serviceList.refresh(false);
			}

			public void dispose() {
				// do nothing
			}

			public Object[] getElements(Object inputElement) {
				return ((List) inputElement).toArray();
			}
		});

		serviceList.setLabelProvider(new LabelProvider() {

			public String getText(Object element) {
				return ((Node) element).selectSingleNode("svcId").getText();
			}
		});

		serviceList.addSelectionChangedListener(new ISelectionChangedListener() {

			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection)event.getSelection();
				area.setServiceDetail((Node) selection.getFirstElement());
			}
		});
	}

	public void setInput(List<Node> serviceRecords) {
		serviceList.setInput(serviceRecords);
	}

}
